package cn.ys.org.service.impl;

import cn.ys.base.util.PageList;
import cn.ys.org.domain.SystemDictionaryDetail;
import cn.ys.org.mapper.SystemDictionaryDetailMapper;
import cn.ys.org.mapper.SystemDictionaryMapper;
import cn.ys.org.query.SystemDictionaryDetailQuery;
import cn.ys.org.service.SystemDictionaryDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SystemDictionaryDetailDetailServiceImpl implements SystemDictionaryDetailService {

    @Autowired
    private SystemDictionaryDetailMapper mapper;

    @Override
    public List<SystemDictionaryDetail> findAll() {
        return mapper.findAll();
    }

    @Override
    public SystemDictionaryDetail findById(Long id) {
        return mapper.findById(id);
    }

    @Override
    public void add(SystemDictionaryDetail systemDictionaryDetail) {
        mapper.add(systemDictionaryDetail);
    }

    @Override
    public void update(SystemDictionaryDetail systemDictionaryDetail) {
        mapper.update(systemDictionaryDetail);
    }

    @Override
    public void delete(Long id) {
        mapper.delete(id);
    }

    @Override
    public PageList<SystemDictionaryDetail> queryByPage(SystemDictionaryDetailQuery query) {
        Integer totals = mapper.queryByCount(query);
        if (null == totals || 0 == totals) {
            return new PageList<SystemDictionaryDetail>(0, new ArrayList<>());
        }
        List<SystemDictionaryDetail> rows = mapper.queryByPage(query);
        return new PageList<>(totals, rows);
    }

    @Override
    public void piDeleteById(List<Long> ids) {
        mapper.piDeleteById(ids);
    }

    @Override
    public List<SystemDictionaryDetail> deptTree() {
        // 查询所有数据
        List<SystemDictionaryDetail> allDepts = mapper.findAll();
        Map<Integer, SystemDictionaryDetail> deptMap = allDepts.stream().collect(Collectors.toMap(SystemDictionaryDetail::getId, dept -> dept));
        List<SystemDictionaryDetail> result = new ArrayList<>();
        for (SystemDictionaryDetail dept : allDepts) {
            if (null == dept.getTypesId()){
                result.add(dept);
            }else {
                SystemDictionaryDetail parent = deptMap.get(dept.getTypesId());
                if (null != parent){
                    parent.getChildren().add(dept);
                }
            }
        }
        return result;
    }

    @Override
    public List<SystemDictionaryDetail> findDictionary(Integer sdId) {
        return mapper.findDictionary(sdId);
    }
}
